package common.util;

import common.Node;
import lombok.experimental.UtilityClass;

import java.util.*;

/**
 * @author : wenchao.long
 * @date : Created in 2021/7/15 10:50 周四
 * @description :
 */
@UtilityClass
public class NodeUtil {

    /**
     * n叉树 用null 分割数字
     */
    public static int NULL_MAX = 2;

    public static Node newInstance(int val) {
        return new Node(val);
    }

    public static Node create(Integer... nums) {
        if (nums == null) {
            return null;
        }
        Deque<Integer> integers = new LinkedList<>(Arrays.asList(nums));
        return create(integers);
    }

    public static void levelOrderList(Node root) {
        if (root == null) {
            return;
        }
        List<List<Integer>> result = new LinkedList<>();
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new LinkedList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node node = queue.remove();
                list.add(node.val);
                List<Node> children = node.children;
                if (children != null && !children.isEmpty()) {
                    queue.addAll(children);
                }
            }
            result.add(list);
        }
        System.out.println(result);
    }

    private static Node create(Deque<Integer> integers) {
        Node root;
        Integer val = integers.remove();
        if (val == null) {
            return null;
        }
        root = newInstance(val);
        Deque<Node> deque = new LinkedList<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            Node poll = deque.poll();
            List<Node> children = new ArrayList<>();
            int b = 0;
            while (b != NULL_MAX) {
                Integer num = integers.poll();
                if (num == null) {
                    b++;
                    continue;
                }
                Node node = newInstance(num);
                deque.add(node);
                children.add(node);
            }
            if (poll != null) {
                poll.children = children.isEmpty() ? null : children;
            }
        }
        return root;
    }
}
